package com.fast.develop.dm.core.reader;

import cn.hutool.core.io.FileUtil;
import com.fast.develop.dm.core.source.MetaDomainSources;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 莫寅
 * @createTime 2022-06-07 18:23
 * @desc：
 */
public class MetaFileReader {

    private MetaDomainSources metaDomainSources;

    private List<InputStream> schemas = new ArrayList<>();

    private String DEFAULT_PATH = "classpath:.schema";

    public MetaFileReader(MetaDomainSources metaDomainSources) {
        this.metaDomainSources = metaDomainSources;
    }

    public MetaFileReader() {
        this.metaDomainSources = new MetaDomainSources();
    }

    public void read(){
        List<String> folders = metaDomainSources.getSchemaFolderPaths();
        if(folders.isEmpty()){
            read(DEFAULT_PATH);
        }else{
            folders.forEach(s -> {
                read(s);
            });
        }
    }

    private void read(String path){
        List<File> files = FileUtil.loopFiles(path, new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if(pathname.getName().indexOf(".json") != -1){
                    return true;
                }
                return false;
            }
        });

        List<InputStream> fileInputStreams = files.stream().map(file -> {
            try {
                return new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            return null;
        }).collect(Collectors.toList());

        schemas.addAll(metaDomainSources.getJsonInputStreams());
        schemas.addAll(fileInputStreams);
    }


    public MetaDomainSources getMetaDomainSources() {
        return metaDomainSources;
    }

    public List<InputStream> getSchemas() {
        return schemas;
    }
}
